package com.qzimp.fujiancuo.utils;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;

import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qzimp.fujiancuo.config.TencentOSSConfig;
import com.qzimp.fujiancuo.entity.vo.ResultCode;
import com.qzimp.fujiancuo.entity.vo.StatusCode;
import com.qzimp.fujiancuo.exceptions.ApiException;
import org.springframework.beans.factory.annotation.Value;


import java.io.File;

/**
 * @className:TencentOSSUtil
 * @author:wuzongbo
 * @date: 2023/8/1
 **/

public class TencentOSSUtil {


    public static COSClient getCOSClient() {

        //建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        COSCredentials cred = new BasicCOSCredentials(TencentOSSConfig.secretId, TencentOSSConfig.secretKey);
// 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(TencentOSSConfig.ap);
        ClientConfig clientConfig = new ClientConfig(region);
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.http);
// 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        if(cosClient==null) throw new ApiException(ResultCode.CUSTOM_ERROR,"OSSClient客户端初始化失败");
        return cosClient;
    }
    public static String upload(File localFile,String targetName){

        PutObjectRequest putObjectRequest = new PutObjectRequest(TencentOSSConfig.bucketName, targetName, localFile);
        COSClient cosClient=getCOSClient();
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        StringBuilder sb=new StringBuilder();
        sb.append("https://");
        sb.append(TencentOSSConfig.bucketName);
        sb.append(".cos.");
        sb.append(TencentOSSConfig.ap);
        sb.append(".myqcloud.com/");
        return sb.toString() ;
    }

}